package contest.oop.sse.key;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class FileKeyLoader implements KeyLoader {
    private PrivateKey privateKey;
    private PublicKey publicKey;

    public FileKeyLoader(String filePath) {
        String[] strBuffer = new String[2];
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            KeyFactory factory = KeyFactory.getInstance("RSA");
            strBuffer[0] = reader.readLine();
            strBuffer[1] = reader.readLine();
            privateKey = factory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(strBuffer[0].getBytes(StandardCharsets.UTF_8))));
            publicKey = factory.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(strBuffer[1].getBytes(StandardCharsets.UTF_8))));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PrivateKey obtainPrivateKey(String keyId) {
        return privateKey;
    }

    @Override
    public PublicKey obtainPublicKey(String keyId) {
        return publicKey;
    }
}
